class Solution(object):
    def wordPuzzle(self, grid, target):
        """
        :type grid: List[List[str]]
        :type target: str
        :rtype: bool
        """
        if not grid or not grid[0]:
            return False
            
        rows, cols = len(grid), len(grid[0])
        directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]  # 上、下、左、右
        
        def backtrack(r, c, idx):
            # 终止条件：已找到完整单词
            if idx == len(target):
                return True
            # 检查越界、字符不匹配或已访问
            if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != target[idx]:
                return False
            # 标记当前单元格为已访问
            original_char = grid[r][c]
            grid[r][c] = '#'  # 使用特殊字符标记
            # 尝试四个方向
            for dr, dc in directions:
                if backtrack(r + dr, c + dc, idx + 1):
                    return True
            # 回溯：恢复当前单元格状态
            grid[r][c] = original_char
            return False
        
        # 遍历每个单元格作为起点
        for r in range(rows):
            for c in range(cols):
                if backtrack(r, c, 0):
                    return True
        return False